package com.sgb.kjwl.view.ui.activity.self.shop;

import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Rect;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityShopCompanyBinding;
import com.sgb.kjwl.di.shopping.DaggerShopComponent;
import com.sgb.kjwl.di.shopping.ShopModule;
import com.sgb.kjwl.model.entity.ShopInfoEntity;
import com.sgb.kjwl.view.ui.adapter.shopping.ShopCompanyImgAdapter;
import com.sgb.kjwl.viewmodel.shopping.ShopCompanyModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MLog;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.inject.Inject;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

/**
 * Author chenfangkai
 */
public class ShopCompanyInfoActivity extends AppActivity {
    public static final String KEY_TYPE = "type";
    private boolean isShow = false;
    private ActivityShopCompanyBinding binding;
    private ShopCompanyImgAdapter adapter;
    private ShopCompanyImgAdapter adapterCertificate;
    private SensorManager sensorManager;
    private SensorEventListener sensorEventListener;
    private ShopInfoEntity shopInfoEntity;

    @Inject
    ShopCompanyModel viewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new JCVideoPlayer.JCAutoFullscreenListener();
    }


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerShopComponent.builder()
                .appComponent(appComponent)
                .shopModule(new ShopModule(this))
                .build()
                .inject(this);
    }

    public static void start(Context context, ShopInfoEntity shopInfoEntity) {
        Intent intent = new Intent(context, ShopCompanyInfoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("shopInfoEntity", shopInfoEntity);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void startById(Context context, String id) {
        Intent intent = new Intent(context, ShopCompanyInfoActivity.class);
        intent.putExtra("id", id);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void initView() {
        shopInfoEntity = (ShopInfoEntity) getIntent().getSerializableExtra("shopInfoEntity");
        String id = getIntent().getStringExtra("id");
        binding = DataBindingUtil.setContentView(ShopCompanyInfoActivity.this, R.layout.activity_shop_company);
        Map map = new HashMap();
        if (TextUtils.isEmpty(id)) {
            map.put("id", shopInfoEntity.getId());
        } else {
            map.put("id", id);
        }
        viewModel.shopDetail(map);
//        binding.setViewModel(shopInfoEntity);
        binding.include.ivBack.setOnClickListener(this);
        binding.include.titleView.setText(getResources().getString(R.string.shop_info));


        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
        GridLayoutManager layoutManagerCertificate = new GridLayoutManager(getActivity(), 2);
        if (adapter == null) {
            adapter = new ShopCompanyImgAdapter(getActivity(), null);
        }
        binding.companyImgRv.setLayoutManager(layoutManager);
        binding.companyImgRv.setAdapter(adapter);

        if (adapterCertificate == null) {
            adapterCertificate = new ShopCompanyImgAdapter(getActivity(), null);
        }
        binding.certificateRv.setLayoutManager(layoutManagerCertificate);
        binding.certificateRv.setAdapter(adapterCertificate);
        adapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
//                CompanyShopInfoActivity.start(ShopCompanyInfoActivity.this, "");
            }
        });
        binding.showTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isShow) {
                    binding.contentTv.setMaxLines(10000);
                    binding.showTv.setText("收起");
                    isShow = true;
                } else {
                    binding.contentTv.setMaxLines(3);
                    binding.showTv.setText("展开");
                    isShow = false;
                }

            }
        });

//        binding.contentTv.setText(Html.fromHtml(shopInfoEntity.getIntroduction()));
    }

    public void setData(ShopInfoEntity shopInfoEntity) {
        binding.setViewModel(shopInfoEntity);
        Document doc = Jsoup.parseBodyFragment(shopInfoEntity.getIntroduction());
        MLog.d("", shopInfoEntity.getIntroduction());
        Elements elements = doc.select("img");
        for (Element each : elements) {
            each.attr("style", "width:100%");
        }

        String html = doc.html();
        Document htmlResult = Jsoup.parseBodyFragment(html);
        elements = htmlResult.select("body");
        for (Element each : elements) {
            each.attr("style", "font-size:34px");
        }


        MLog.d("", htmlResult.html());

        binding.videoView.setUp(shopInfoEntity.getVideoUrl(), JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "企业视频");

        if (TextUtils.isEmpty(shopInfoEntity.getIntroduction())) {
            binding.contentView.setVisibility(View.GONE);
            binding.webView.setVisibility(View.GONE);
        } else {
            binding.webView.setVisibility(View.VISIBLE);
            binding.contentView.setVisibility(View.VISIBLE);
            binding.webView.loadData(htmlResult.html(), "text/html; charset=UTF-8", null);
            binding.webView.getSettings().setJavaScriptEnabled(true);
            binding.webView.getSettings().setSupportZoom(false);
            binding.webView.getSettings().setBuiltInZoomControls(false);
            binding.webView.getSettings().setUseWideViewPort(true);
            binding.webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            binding.webView.getSettings().setLoadWithOverviewMode(true);
            binding.webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    binding.webView.loadUrl("javascript:document.body.style.padding=\"6.5%\"; void 0");
                }
            });
        }

        if (shopInfoEntity.getImage().size() > 0) {
            binding.photoView.setVisibility(View.VISIBLE);
            adapter.setDatas(shopInfoEntity.getImage());
        } else {
            binding.photoView.setVisibility(View.GONE);
            adapter.setDatas(null);
        }
        if (!"".equals(shopInfoEntity.getRelevantCertificate())) {
            binding.honorView.setVisibility(View.VISIBLE);
            List<String> certificate = new ArrayList<>(Arrays.asList(Objects.requireNonNull(shopInfoEntity.getRelevantCertificate().split(","))));
            adapterCertificate.setDatas(certificate);
        } else {
            adapterCertificate.setDatas(null);
            binding.honorView.setVisibility(View.GONE);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.call_phone_img:
//                CompanyShopInfoActivity.start(this, "");
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(sensorEventListener);
        JCVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
}
